package com.hnkywl.sts.service.kcgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdRzDao;
import com.hnkywl.sts.dao.kcgl.SskcDao;
import com.hnkywl.sts.entity.base.Sjzdz;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Zjbcd;
import com.hnkywl.sts.entity.cggl.ZjbcdRz;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.base.WebserviceTransService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.xsgl.XsdService;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-4-30
 * Time: 上午11:32
 * To change this template use File | Settings | File Templates.
 */
@Service
public class SskcService {
    private SskcDao sskcDao;
    private ZjbcdDao zjbcdDao;
    private ZjbcdRzDao zjbcdRzDao;
    private XsdService xsdService;
    private CgdDao cgdDao;
    private WebserviceTransService webserviceTransService;

    //实时库存查询列表
    public String findSskcList(String chtbm, String xhtbm, String qdrqstart, String qdrqend, String xsxt_xsdh, String carno, String bindno, String fhrq, String ckrqstart, String ckrqend, String sskczt, int pageNo, int pageSize) {
        Page<Map> page = sskcDao.findSskcList(chtbm, xhtbm, qdrqstart, qdrqend, xsxt_xsdh, carno, bindno, fhrq, ckrqstart, ckrqend, sskczt, pageNo, pageSize);
        List<Map> sumList = sskcDao.findSumSskc(chtbm, xhtbm, qdrqstart, qdrqend, xsxt_xsdh, carno, bindno, fhrq, ckrqstart, ckrqend, sskczt);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String json = gson.toJson(page.getResult());
        Double kkdsl = 0d;
        Double wsje = 0d;
        Double js = 0d;
        Double rksl = 0d;
        Double rkjs = 0d;
        if (sumList.size() != 0) {
            for (Map map : sumList) {
                rksl += Double.valueOf((map.get("rksl") == null ? 0d : map.get("rksl")).toString());
                js += Double.valueOf((map.get("js") == null ? 0d : map.get("js")).toString());
                kkdsl += Double.valueOf((map.get("kkdsl") == null ? 0d : map.get("kkdsl")).toString());
                wsje += Double.valueOf((map.get("sjje") == null ? 0d : map.get("sjje")).toString());
                rkjs += Double.valueOf((map.get("rkjs") == null ? 0d : map.get("rkjs")).toString());
            }
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"xhtbm\":\"合计:\",\"rkjs\":" + rkjs +  ",\"rksl\":" + rksl +",\"js\":" + js + ",\"kkdsl\":" + kkdsl + ",\"wsje\":" + wsje + " }]}";
        } else {
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + "}";
        }

    }

//    public String findList(String xsxt_xsdh, String sbgsJc, String cggsJc, String code, String ckmc, Long gysId, Long ckId, String jtwzname, String cgdh,
//                           String khbm, String qk, Date endDate, String wzmc, int pageNo, int pageSize) {
//        Page<Map> page = sskcDao.findList(xsxt_xsdh, sbgsJc, cggsJc, code, ckmc, gysId, ckId, jtwzname, cgdh, khbm, qk, endDate, wzmc, pageNo, pageSize);
//        List<Map> sumList = sskcDao.findSumKh(xsxt_xsdh, sbgsJc, cggsJc, code, ckmc, gysId, ckId, jtwzname, cgdh, khbm, qk, endDate, wzmc);
//        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
//        String json = gson.toJson(page.getResult());
//        Double kkdsl = 0d;
//        Double wsje = 0d;
//        Double sl = 0d;
//        Double js = 0d;
//        Double rksl = 0d;
//        if (sumList.size() != 0) {
//            for (Map map : sumList) {
//                rksl += Double.valueOf((map.get("sumrksl") == null ? 0d : map.get("sumrksl")).toString());
//                js += Double.valueOf((map.get("js") == null ? 0d : map.get("js")).toString());
//                sl += Double.valueOf((map.get("sumsl") == null ? 0d : map.get("sumsl")).toString());
//                kkdsl += Double.valueOf((map.get("sumkkdsl") == null ? 0d : map.get("sumkkdsl")).toString());
//                wsje += Double.valueOf((map.get("wsje") == null ? 0d : map.get("wsje")).toString());
//            }
//            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"xhtbm\":\"合计:\",\"rksl\":" + rksl + ",\"js\":" + js + ",\"kkdsl\":" + kkdsl + ",\"wsje\":" + wsje + " }]}";
//        } else {
//            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + "}";
//        }
//
//    }

    /**
     * 查询商户信息
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public String findBuyerInfoList(String code, String wzmc, String ggxh, String gysName, int pageNo, int pageSize) {
        Page<Map> page = sskcDao.findBuyerInfoList(code, wzmc, ggxh, gysName, pageNo, pageSize);
        Page<Map> sumList = sskcDao.findBuyerInfoListToSum(code, wzmc, ggxh, gysName, pageNo, pageSize);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String json = gson.toJson(page.getResult());
        List<Map> maps = sumList.getResult();
        Double sbjs = 0d;
        Double sbsl = 0d;
        Double rkjs = 0d;
        Double rksl = 0d;
        Double ckjs = 0d;
        Double cksl = 0d;
        Double gdjs = 0d;
        Double gdsl = 0d;
        Double syjs = 0d;
        Double sysl = 0d;
        if (maps.size() != 0) {
            for (Map map : maps) {
                sbjs = Double.valueOf((map.get("sbjs") == null ? 0d : map.get("sbjs")).toString());
                sbsl = Double.valueOf((map.get("sbsl") == null ? 0d : map.get("sbsl")).toString());
                rkjs = Double.valueOf((map.get("rkjs") == null ? 0d : map.get("rkjs")).toString());
                rksl = Double.valueOf((map.get("rksl") == null ? 0d : map.get("rksl")).toString());
                ckjs = Double.valueOf((map.get("ckjs") == null ? 0d : map.get("ckjs")).toString());
                cksl = Double.valueOf((map.get("cksl") == null ? 0d : map.get("cksl")).toString());
                gdjs = Double.valueOf((map.get("gdjs") == null ? 0d : map.get("gdjs")).toString());
                gdsl = Double.valueOf((map.get("gdsl") == null ? 0d : map.get("gdsl")).toString());
                syjs = Double.valueOf((map.get("syjs") == null ? 0d : map.get("syjs")).toString());
                sysl = Double.valueOf((map.get("sysl") == null ? 0d : map.get("sysl")).toString());
            }
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"QC\":\"合计:\",\"sbjs\":" + sbjs + ",\"sbsl\":" + sbsl + ",\"rkjs\":" + rkjs + ",\"rksl\":" + rksl + ",\"ckjs\":" + ckjs + ",\"cksl\":" + cksl + ",\"gdjs\":" + gdjs + ",\"gdsl\":" + gdsl + ",\"syjs\":" + syjs + ",\"sysl\":" + sysl + " }]}";
        } else {
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + "}";
        }
    }

    public String findYkbbList(String htbm, String gysName, int pageNo, int pageSize) {
        Page<Map> page = sskcDao.findYkbbList(htbm, gysName, pageNo, pageSize);
        Page<Map> sumList = sskcDao.findYkbbListToSum(htbm, gysName, pageNo, pageSize);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String json = gson.toJson(page.getResult());
        List<Map> maps = sumList.getResult();
        Double cgje = 0d;
        Double kcje = 0d;
        Double xsje = 0d;
        Double ykje = 0d;
        if (maps.size() != 0) {
            for (Map map : maps) {
                cgje += Double.valueOf((map.get("cgje") == null ? 0d : map.get("cgje")).toString());
                kcje += Double.valueOf((map.get("kcje") == null ? 0d : map.get("kcje")).toString());
                xsje += Double.valueOf((map.get("xsje") == null ? 0d : map.get("xsje")).toString());
                ykje += Double.valueOf((map.get("ykje") == null ? 0d : map.get("ykje")).toString());
            }
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"HTBM\":\"合计:\",\"cgje\":" + cgje + ",\"xsje\":" + xsje + ",\"kcje\":" + kcje + ",\"ykje\":" + ykje + " }]}";
        } else {
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + "}";
        }
    }

    public List<Map> findByifChart(String code, String wzmc, String ggxh, String gysName) {
        Page<Map> sumList = this.sskcDao.findByifCharts(code, wzmc, ggxh, gysName, 1, 10000);
        return sumList.getResult();
    }

    public String createJsonFromInfo(String name, String standardMode, Gsjg gsjg, String pageNo, String pageSize) {
        Page<Map> page = sskcDao.findBuyerInfoList(null, name, standardMode, gsjg.getQc(), Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Map> list = page.getResult();
        StringBuffer sb = new StringBuffer();
        if (list != null) {
            sb.append("{\"code\":\"").append("0").append("\",");
            sb.append("\"message\":\"").append("查询成功!").append("\",");
            sb.append("\"page\":").append("{");
            sb.append("\"totalCount\":\"").append(page.getTotalCount()).append("\",");
            sb.append("\"pageSize\":\"").append(pageNo).append("\",");
            sb.append("\"pageNo\":\"").append(pageSize).append("\"");
            sb.append("},").append("\"items\":[");
            for (Map map : list) {
                sb.append("{\"companyName\":\"").append((String) map.get("QC")).append("\",");
                sb.append("\"name\":\"").append((String) map.get("NAME")).append("\",");
                sb.append("\"nameCode\":\"").append((String) map.get("CODE")).append("\",");
                sb.append("\"standardMode\":\"").append((String) map.get("GGXH")).append("\",");
                sb.append("\"unitName\":\"").append((String) map.get("DW")).append("\",");
                sb.append("\"fieldName\":\"").append((String) map.get("Z") == null ? "" : (String) map.get("Z")).append("\",");
                sb.append("\"reportItem\":\"").append(map.get("sbjs").toString()).append("\",");
                sb.append("\"reportNumber\":\"").append(map.get("sbsl").toString()).append("\",");
                sb.append("\"inWarehouseItem\":\"").append(map.get("rkjs").toString()).append("\",");
                sb.append("\"inWarehouseNumber\":\"").append(map.get("rksl").toString()).append("\",");
                sb.append("\"outWarehouseItem\":\"").append(map.get("ckjs").toString()).append("\",");
                sb.append("\"outWarehouseNumber\":\"").append(map.get("cksl").toString()).append("\",");
                sb.append("\"hangResourceItem\":\"").append(map.get("gdjs").toString()).append("\",");
                sb.append("\"hangResourceNumber\":\"").append(map.get("gdsl").toString()).append("\",");
                sb.append("\"surplusItem\":\"").append(map.get("syjs").toString()).append("\",");
                sb.append("\"surplusNumber\":\"").append(map.get("sysl").toString()).append("\"},");
            }
            sb = sb.delete(sb.length() - 1, sb.length());
            sb.append("]}");
        } else {
            sb.append("{\"code\":\"1\",\"message\":\"根据参数查询list为空\"}");
        }
        return sb.toString();
    }
    //################################挂单方法#############################################

    //根据卡号IDs找到卡号集合

    public String findWzMxFromKhIDs(String khIds) {
        String[] khStr = khIds.split(",");
        List<Long> khIdList = new ArrayList<Long>();
        for (int i = 0; i < khStr.length; i++) {
            khIdList.add(Long.parseLong(khStr[i]));
        }
        Gson gson = new Gson();
        List<Map> khlist = this.sskcDao.findSskcGdWzmxFromKhIds(khIdList);
        String result = "";
        result = "{\"rows\":" + gson.toJson(khlist) + "}";
        return result;
    }

    //挂单方法
    @Transactional
    public List<Map<String, Object>> gd(List<Kh> khList) throws SQLException {
        List<Kh> khs = new ArrayList<Kh>();
        for (Kh kh : khList) {
            Kh newKh = new Kh();
            newKh = sskcDao.get(kh.getId());
            newKh.setGdsl(kh.getGdsl());
            newKh.setGdjs(kh.getGdjs());
            newKh.setGdslhj(newKh.getGdslhj() == null ? 0 : newKh.getGdslhj() + kh.getGdsl());
            newKh.setGdjshj(newKh.getGdjshj() == null ? 0 : newKh.getGdjshj() + kh.getGdjs());
            Double jz = (double) (Math.round((kh.getGdsl() / kh.getGdjs()) * 1000000) / 1000000.0);
            newKh.setJz(jz);
            khs.add(newKh);
            sskcDao.save(newKh);
        }
        String json = xsdService.createJsonToInterFace(null, khs);
        if (khList != null) {
            String result =null;
            Gson gson = new Gson();
            List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
            map = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
            return map;
        }
        return null;
    }


    public String analyzeMapCgdh(String str) {
        String[] strings = str.split("-");
        return strings[0] + "-" + strings[1] + "第" + strings[2] + "物资挂单失败;";
    }

    @Transactional
    public void gdChangeKhKkdsl(String str) {
        String[] strings = str.split("-");
        Cgd cgd = cgdDao.findCgdFindCgdh(strings[0] + "-" + strings[1]);
        List<Kh> khList = cgd.getKhList();
        for (Kh kh : khList) {
            if (kh.getPxh() == Integer.parseInt(strings[2])) {
                kh.setKkdsl(kh.getKkdsl() - kh.getGdsl());
                sskcDao.save(kh);
            }
        }
    }

    public Kh checkExist(String rsn) {
        String hql = "from Kh where resource_serial_number_1 = ?";
        List<Kh> khList = this.sskcDao.find(hql, rsn);
        if (null != khList && khList.size() > 0) {
            return khList.get(0);
        }
        return null;
    }

    //#############################################################################

    @Transactional
    public Kh findKhDetail(Long id) {
        return this.sskcDao.get(id);
    }

    @Transactional
    public void changeStatus(Long id, String status) {
        Kh kh1 = this.findKhDetail(id);
        /*  Yg kpr = YgService.getCurrentYg();
       cgjsd.setKpr(kpr);
       cgjsd.setKprq(new Date());*/
        kh1.setQk(status.equals("true"));
        this.sskcDao.save(kh1);
    }

    //实时库存明细
    @Transactional
    public Kh findSskcDetail(Long id) {
        return this.sskcDao.get(id);
    }

    /**
     * 库存成本调整
     *
     * @param kh
     */
    @Transactional
    public void kccbtz(Kh kh) {
        Kh k = sskcDao.get(kh.getId());
        if (k.getQk()) {
            throw new RuntimeException("已清卡，不能进行调整！");
        }
        if (k.getWsdj().doubleValue() != kh.getWsdj().doubleValue()) {
            Zjbcd zjbcd = new Zjbcd();
            Sjzdz sjzdz = new Sjzdz();
            sjzdz.setId(50L);
            zjbcd.setLb(sjzdz);
            java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
            String slstr = df.format((kh.getWsdj() - k.getWsdj()) * kh.getSl());
            zjbcd.setJe(Double.parseDouble(slstr));
            zjbcd.setZt("ybc");
            if (kh.getGys() != null)
                zjbcd.setGys(kh.getGys());
            else {
                Gsjg gsjg = new Gsjg();
                gsjg.setId(-1l);
                zjbcd.setGys(gsjg);
            }
            zjbcd.setCreateUser(YgService.getCurrentYg());
            zjbcd.setDateCreated(new Date());
            zjbcd.setLastUpdated(zjbcd.getDateCreated());
            zjbcd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            zjbcd.setCreateOrgan(YgService.getCurrentYg().getZggs());
            zjbcd.setSftzsc(true);
            zjbcdDao.save(zjbcd);
            ZjbcdRz zjbcdRz = new ZjbcdRz();
            zjbcdRz.setKh(k);
            zjbcdRz.setZjbcd(zjbcd);
            zjbcdRz.setYkccb(k.getWsdj());
            zjbcdRz.setXkccb(kh.getWsdj());
            zjbcdRz.setCreateUser(YgService.getCurrentYg());
            zjbcdRz.setDateCreated(new Date());
            zjbcdRz.setLastUpdated(zjbcdRz.getDateCreated());
            zjbcdRz.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            zjbcdRz.setCreateOrgan(YgService.getCurrentYg().getZggs());
            zjbcdRzDao.save(zjbcdRz);
            k.setWsdj(kh.getWsdj());
            k.setLastUpdated(new Date());
            sskcDao.save(k);
        }
    }

    public String findjgdSskcList(String sbgsJc, String cggsJc, String code, String ckmc, Long gysId, Long ckId, String jtwzname, String cgdh, String khbm, String qk, String wzmc, String rkdh, int pageNo, int pageSize) {
        Page<Map> page = sskcDao.findjgdSskcList(sbgsJc, cggsJc, code, ckmc, gysId, ckId, jtwzname, cgdh, khbm, qk, wzmc, rkdh, pageNo, pageSize);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String sskcJson = gson.toJson(page.getResult());
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + sskcJson + "}";
    }

    @Autowired
    public void setSskcDao(SskcDao sskcDao) {
        this.sskcDao = sskcDao;
    }

    @Autowired
    public void setZjbcdDao(ZjbcdDao zjbcdDao) {
        this.zjbcdDao = zjbcdDao;
    }

    @Autowired
    public void setZjbcdRzDao(ZjbcdRzDao zjbcdRzDao) {
        this.zjbcdRzDao = zjbcdRzDao;
    }

    @Autowired
    public void setXsdService(XsdService xsdService) {
        this.xsdService = xsdService;
    }

    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

}
